package org.zyj.io.example.case1;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * 连接服务端
 *
 * @author zhouyijin
 * @date 2022-01-14 16:23:09
 */
public class Client1 {

    public static void main(String[] args) throws InterruptedException {
        final EventLoopGroup eventExecutors = new NioEventLoopGroup();
        try {
            final Bootstrap bootstrap = new Bootstrap();
            //设置
            bootstrap.group(eventExecutors)//设置线程组
                    .channel(NioSocketChannel.class)//设置客户端通道的实现类
                    .handler(new ChannelInitializer<SocketChannel>() { //设置处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyClientHandler());//管道中就一个handler
                        }
                    });
            System.out.println("client setup done");

            //启动客户端, 去连接服务器
            final ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9998).sync();//异步启动

            //监听 关闭通道, 阻塞
            channelFuture.channel().closeFuture().sync();
        } finally {
            eventExecutors.shutdownGracefully();
        }


    }

}
